package com.peng.leetcode.list;

/**
 * RemoveNthFromEnd
 * 19 删除链表中倒数第N个节点
 * <p>
 * Created on 2022/12/26
 *
 * @author lupeng
 */
public class RemoveNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode sentry = new ListNode(0);
        sentry.next = head;
        ListNode p1 = sentry;
        ListNode p2 = sentry;
        int i = 0;
        while (p2.next != null) {
            if (i >= n) {
                p1 = p1.next;
            }
            p2 = p2.next;
            i++;
        }
        if (p1.next != null) {
            p1.next = p1.next.next;
        }
        if (i == 0 && n == 1) {
            return null;
        }
        return sentry.next;
    }
}
